<!DOCTYPE html>
<html lang="us">
<head>
    <meta charset="utf-8">
    <title>checkbox赋值测试</title>
    <script src="../../js/common/jquery-3.5.1.js"></script>

</head>
<body>
<h2>checkbox赋值测试</h2>
<br/>

<div class="form-group">
    <label>Checkboxes</label>
    <br/>
    <div class="checkbox">
        <label>
            <input type="checkbox" name="chk" value="101">Checkbox 1
        </label>
    </div>
    <div class="checkbox">
        <label>
            <input type="checkbox" name="chk" value="102">Checkbox 2
        </label>
    </div>
    <div class="checkbox">
        <label>
            <input type="checkbox" name="chk" value="103">Checkbox 3
        </label>
    </div>
    <div class="checkbox">
        <label>
            <input type="checkbox" name="chk" value="104">Checkbox 4
        </label>
    </div>
    <div class="checkbox">
        <label>
            <input type="checkbox" name="chk" value="105">Checkbox 5
        </label>
    </div>
</div>

<br/>

<button class="btn" type="button" id="btnSelectAll">全选</button>
<button class="btn" type="button" id="btnSelectNull">全不选</button>
<button class="btn" type="button" id="btnSelect1and3">选1和3</button>

<button class="btn" type="button" id="btnGetVal">取值</button>

</body>
</html>
<script>

    $(function () {
        $("#btnSelectAll").click(function () {
            selectAll();
        });
        $("#btnSelectNull").click(function () {
            selectNull();
        });
        $("#btnSelect1and3").click(function () {
            select1and3();
        });
        $("#btnGetVal").click(function () {
            getVal();
        });
    });

    function selectAll() {
        $("input[name='chk']").each(function () {
            //$(this).attr("checked", true);
            this.checked = true;
        });
    }

    function selectNull() {
        $("input[name='chk']").each(function () {
            this.checked = false;
        });
    }

    function select1and3() {
        //先清空选项
        selectNull();
        var sel = [];
        sel.push("101");
        sel.push("103");
        for (var i = 0; i < sel.length; i++) {
            $("input[name='chk']").each(function () {
                if ($(this).val() == sel[i]) {
                    this.checked = true;
                }
            });
        }
    }

    function getVal() {
        var chk_value = [];//定义一个数组
        $('input[name="chk"]:checked').each(function () {//遍历每一个名字为nodes的复选框，其中选中的执行函数
            chk_value.push($(this).val());//将选中的值添加到数组chk_value中
        });
        var groups = chk_value.join(",");
        alert(groups);
    }


</script>
